package com.galleryviewpager;

import android.content.Context;
import android.view.View;

import androidx.annotation.NonNull;
import androidx.viewpager.widget.ViewPager;

public class GalleryPagerTransformer implements ViewPager.PageTransformer {

    private int maxTranslateOffsetX;
    private ViewPager viewPager;

    public GalleryPagerTransformer(Context context) {
        this.maxTranslateOffsetX = DensityUtils.dip2px(context, 160);
    }

    @Override
    public void transformPage(@NonNull View page, float position) {
        if (viewPager == null) {
            viewPager = (ViewPager) page.getParent();
        }

        //获取page 在左边屏幕的距离
        int leftInScreen = page.getLeft() - viewPager.getScrollX();

        int centerInViewPager = leftInScreen + page.getMeasuredWidth() / 2;

        int offsetX = centerInViewPager - viewPager.getMeasuredWidth() / 2;

        float offsetRate = (offsetX * 0.38f / viewPager.getMeasuredWidth());

        float scaleFactor = 1 - Math.abs(offsetRate);

        if (scaleFactor > 0) {
            page.setScaleX(scaleFactor);
            page.setScaleY(scaleFactor);
            page.setTranslationX(-maxTranslateOffsetX * offsetRate);
        }
    }
}
